package main;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;

import org.apache.log4j.Logger;

import server.WebServerThread;
import utility.AppUtilities;

public class WebServer {
	private static final Logger log = Logger.getLogger(WebServer.class);

	private static final AppUtilities utilities = AppUtilities.createAppUtilities();
	private static final Properties properties = new Properties();

	public WebServer() {
		try {
			properties.load(utilities.openConfigurationFile("config.properties").openStream());
		}catch (IOException e) {
			log.error(e.getMessage(), e.getCause());
		}
	}

	private final boolean running = true;

	public static void main(String[] args) {
		WebServer webServer = new WebServer();

		/* Display configuration */
		final String nDef = " not defined.";
		log.info("Version " + properties.getProperty("version", nDef));
		log.info("default adress: my.testing.server/index.html");
		log.info("port=" + properties.getProperty("port", nDef));
		log.info("rootDir=" + properties.getProperty("rootDir", nDef));
		log.info("defaulFile=" + properties.getProperty("defaulFile", nDef));

		ServerSocket server;
		try {
			server = new ServerSocket(Integer.valueOf(properties.getProperty("port", "80")));
			int localPort = server.getLocalPort();
			log.info(WebServer.class.getName() + " is listening on port " + localPort + ".");
			do {
				Socket client = server.accept();
				Thread t = new Thread(new WebServerThread(client, properties));

				t.setDaemon(true);
				t.start();
			}while (webServer.running);
		}catch (IOException e) {
			log.error(e.getMessage(), e.getCause());
		}
	}
}
